<template>
  <view class="container">
    <view class="header">
      <view class="header-left" @tap="navigateBack">
        <text class="back-icon">←</text>
      </view>
      <text class="header-title">评估详情</text>
      <view class="header-right"></view>
    </view>

    <view class="assessment-container">
      <!-- 加载中 -->
      <view v-if="loading" class="loading-container">
        <u-loading size="24" color="#FF7A45"></u-loading>
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 评估详情内容 -->
      <view v-else-if="assessmentDetails" class="assessment-content">
        <!-- 患者基本信息卡片 -->
        <view class="info-card">
          <text class="card-title">患者信息</text>
          <view class="patient-info">
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">姓名：</text>
                <text class="info-value">{{ patientInfo.name || '未知' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">性别：</text>
                <text class="info-value">{{ patientInfo.gender === 1 ? '男' : '女' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">年龄：</text>
                <text class="info-value">{{ patientInfo.age || '未知' }}岁</text>
              </view>
            </view>
            
            <!-- 更多患者信息 -->
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">联系电话：</text>
                <text class="info-value">{{ patientInfo.phone || '未提供' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">身份证号：</text>
                <text class="info-value">{{ patientInfo.id_card || '未提供' }}</text>
              </view>
            </view>
            
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">科室：</text>
                <text class="info-value">{{ patientInfo.department || '未提供' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">主治医生：</text>
                <text class="info-value">{{ patientInfo.doctor || '未提供' }}</text>
              </view>
            </view>
            
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">初诊日期：</text>
                <text class="info-value">{{ patientInfo.first_visit_date || '未提供' }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 评估结果概览卡片 -->
        <view class="overview-card">
          <text class="card-title">评估结果概览</text>
          <view class="assessment-overview">
            <!-- 只显示已填写的量表 - 基于scaleDetails的存在性 -->
            <view v-if="scaleDetails && scaleDetails.hamd" class="overview-item">
              <text class="overview-label">抑郁量表（HAMD）</text>
              <text class="overview-value" :class="getSeverityClass('hamd', assessmentDetails.hamd_total)">{{ assessmentDetails.hamd_total }}</text>
              <text class="severity-text">{{ getSeverityText('hamd', assessmentDetails.hamd_total) }}</text>
            </view>
            <view v-if="scaleDetails && scaleDetails.hama" class="overview-item">
              <text class="overview-label">焦虑量表（HAMA）</text>
              <text class="overview-value" :class="getSeverityClass('hama', assessmentDetails.hama_total)">{{ assessmentDetails.hama_total }}</text>
              <text class="severity-text">{{ getSeverityText('hama', assessmentDetails.hama_total) }}</text>
            </view>
            <view v-if="scaleDetails && scaleDetails.ymrs" class="overview-item">
              <text class="overview-label">躁狂量表（YMRS）</text>
              <text class="overview-value" :class="getSeverityClass('ymrs', assessmentDetails.ymrs_total)">{{ assessmentDetails.ymrs_total }}</text>
              <text class="severity-text">{{ getSeverityText('ymrs', assessmentDetails.ymrs_total) }}</text>
            </view>
            
            <!-- 如果没有任何量表数据，显示提示 -->
            <view v-if="!hasAnyScaleData" class="no-data">
              <text class="no-data-text">暂无评估数据</text>
            </view>
            <view class="overview-item">
              <text class="overview-label">评估日期</text>
              <text class="overview-value">{{ assessmentDetails.assessment_date }}</text>
            </view>
          </view>
        </view>
        
        <!-- 评估备注卡片 -->
        <view class="notes-card">
          <text class="card-title">评估备注</text>
          <text class="notes-content">{{ assessmentDetails.assessment_notes || '无' }}</text>
        </view>
        
        <!-- 量表答案详情卡片 -->
        <view class="scale-card">
          <text class="card-title">量表答案详情</text>
          
          <!-- 抑郁量表答案 -->
          <view v-if="scaleDetails && scaleDetails.hamd" class="scale-section">
            <text class="scale-title">抑郁量表（HAMD）</text>
            <view class="scale-answers">
              <view v-for="(answer, index) in scaleDetails.hamd" :key="'hamd-' + index" class="scale-answer-item">
                <text class="answer-number">{{ index + 1 }}.</text>
                <text class="answer-value">{{ answer }}</text>
              </view>
            </view>
          </view>
          
          <!-- 焦虑量表答案 -->
          <view v-if="scaleDetails && scaleDetails.hama" class="scale-section">
            <text class="scale-title">焦虑量表（HAMA）</text>
            <view class="scale-answers">
              <view v-for="(answer, index) in scaleDetails.hama" :key="'hama-' + index" class="scale-answer-item">
                <text class="answer-number">{{ index + 1 }}.</text>
                <text class="answer-value">{{ answer }}</text>
              </view>
            </view>
          </view>
          
          <!-- 躁狂量表答案 -->
          <view v-if="scaleDetails && scaleDetails.ymrs" class="scale-section">
            <text class="scale-title">躁狂量表（YMRS）</text>
            <view class="scale-answers">
              <view v-for="(answer, index) in scaleDetails.ymrs" :key="'ymrs-' + index" class="scale-answer-item">
                <text class="answer-number">{{ index + 1 }}.</text>
                <text class="answer-value">{{ answer }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 无数据状态 -->
      <view v-else class="no-data">
        <text class="no-data-text">暂无评估数据</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getPatientAssessmentDetails } from '../../../utils/api/doctor'
import { getUserInfo } from '../../../utils/auth.js';

export default {
  data() {
    return {
      loading: false,
      assessmentDetails: null,
      scaleDetails: null,
      patientInfo: {},
      patientUserId: ''
    }
  },
  
  computed: {
    // 检查是否有任何量表数据 - 基于scaleDetails的存在性
    hasAnyScaleData() {
      return (this.scaleDetails && this.scaleDetails.hamd) ||
             (this.scaleDetails && this.scaleDetails.hama) ||
             (this.scaleDetails && this.scaleDetails.ymrs);
    }
  },
  
  onLoad(options) {
    // 从页面参数中获取患者ID和评估ID
    if (options.patientUserId && options.assessmentId) {
      this.patientUserId = options.patientUserId
      this.getAssessmentDetails(options.assessmentId)
      this.getPatientInfo(options.patientUserId)
    }
  },
  methods: {
    // 返回上一页
    navigateBack() {
      uni.navigateBack()
    },
    
    // 获取评估详情
    async getAssessmentDetails(assessmentId) {
      this.loading = true
      try {
        // 使用模拟数据，根据不同的assessmentId返回不同的评估数据
        let mockData
        
        switch(assessmentId) {
          case '101':
            mockData = {
              code: 200,
              data: {
                assessment: {
                  id: assessmentId,
                  user_id: this.patientUserId,
                  assessment_date: '2023-09-15',
                  hamd_total: 18,
                  hama_total: 22,
                  ymrs_total: 5,
                  assessment_notes: '患者近期情绪低落，对日常活动缺乏兴趣，睡眠质量差，入睡困难，早醒。食欲减退，体重下降约3kg。注意力不集中，工作效率下降。但有治疗意愿，愿意配合药物治疗和心理干预。'
                },
                scales: {
                  hamd: [3, 2, 1, 3, 2, 3, 2, 2, 1, 3, 2, 1, 2, 0, 1, 2, 1],
                  hama: [3, 3, 2, 3, 2, 3, 2, 2, 1, 2, 1, 0, 2, 1],
                  ymrs: [1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0]
                }
              }
            }
            break
          case '102':
            mockData = {
              code: 200,
              data: {
                assessment: {
                  id: assessmentId,
                  user_id: this.patientUserId,
                  assessment_date: '2023-09-10',
                  hamd_total: 12,
                  hama_total: 8,
                  ymrs_total: 18,
                  assessment_notes: '患者表现为情绪高涨，言语增多，活动量增加，睡眠需求减少。注意力容易分散，自我评价过高，有夸大观念。建议密切观察，适当调整治疗方案。'
                },
                scales: {
                  hamd: [2, 1, 0, 2, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1],
                  hama: [1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0],
                  ymrs: [3, 3, 3, 2, 2, 3, 2, 3, 3, 2, 3]
                }
              }
            }
            break
          case '103':
            mockData = {
              code: 200,
              data: {
                assessment: {
                  id: assessmentId,
                  user_id: this.patientUserId,
                  assessment_date: '2023-09-05',
                  hamd_total: 5,
                  hama_total: 24,
                  ymrs_total: 3,
                  assessment_notes: '患者主要表现为焦虑症状，坐立不安，紧张害怕，有濒死感。伴有心悸、出汗、手抖等躯体症状。睡眠障碍明显，难以入睡，易惊醒。建议增加抗焦虑药物剂量，并进行放松训练。'
                },
                scales: {
                  hamd: [1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1],
                  hama: [4, 4, 3, 4, 3, 2, 3, 3, 2, 3, 2, 1, 3, 2],
                  ymrs: [0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0]
                }
              }
            }
            break
          default:
            // 默认数据
            mockData = {
              code: 200,
              data: {
                assessment: {
                  id: assessmentId,
                  user_id: this.patientUserId,
                  assessment_date: '2023-09-15',
                  hamd_total: 18,
                  hama_total: 22,
                  ymrs_total: 5,
                  assessment_notes: '患者最近情绪低落，睡眠质量差，但有治疗意愿'
                },
                scales: {
                  hamd: [3, 2, 1, 3, 2, 3, 2, 2, 1, 3, 2, 1, 2, 0, 1, 2, 1],
                  hama: [3, 3, 2, 3, 2, 3, 2, 2, 1, 2, 1, 0, 2, 1],
                  ymrs: [1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0]
                }
              }
            }
        }
        
        this.assessmentDetails = mockData.data.assessment
        this.scaleDetails = mockData.data.scales
        
        // 实际API调用
        /*
        const res = await getPatientAssessmentDetails(assessmentId)
        if (res.code === 200 && res.data) {
          this.assessmentDetails = res.data.assessment
          this.scaleDetails = res.data.scales
        } else {
          uni.showToast({
            title: '获取评估详情失败',
            icon: 'none'
          })
        }
        */
      } catch (error) {
        console.error('获取评估详情失败:', error)
        uni.showToast({
          title: '获取评估详情失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 获取患者信息
    async getPatientInfo(patientUserId) {
      try {
        // 使用模拟数据，根据不同的patientUserId返回不同的患者信息
        switch(patientUserId) {
          case '1':
            this.patientInfo = {
              name: 'Henry Chen',
              gender: 1,
              age: 23,
              phone: '138****1234',
              id_card: '3****************X',
              department: '精神科',
              doctor: '张医生',
              first_visit_date: '2023-08-01'
            }
            break
          case '2':
            this.patientInfo = {
              name: 'Jimmy Liu',
              gender: 1,
              age: 20,
              phone: '139****5678',
              id_card: '4****************Y',
              department: '心理科',
              doctor: '李医生',
              first_visit_date: '2023-08-15'
            }
            break
          case '3':
            this.patientInfo = {
              name: 'Amy Wang',
              gender: 0,
              age: 24,
              phone: '137****9012',
              id_card: '5****************Z',
              department: '精神科',
              doctor: '王医生',
              first_visit_date: '2023-09-01'
            }
            break
          default:
            this.patientInfo = {
              name: '测试患者',
              gender: 1,
              age: 25
            }
        }
        
        // 实际API调用
        /*
        // 从本地存储获取用户信息或通过API获取
        const userInfo = await getUserInfo(patientUserId)
        if (userInfo) {
          this.patientInfo = userInfo
        }
        */
      } catch (error) {
        console.error('获取患者信息失败:', error)
      }
    },
    
    // 格式化日期 - 修复iOS兼容性问题
    formatDate(dateString) {
      if (!dateString) return '';
      
      try {
        let date;
        
        // 处理不同的日期格式，确保iOS兼容性
        if (typeof dateString === 'string') {
          // 将 "YYYY-MM-DD HH:mm:ss" 格式转换为 "YYYY/MM/DD HH:mm:ss"
          const isoDate = dateString.replace(' ', 'T');
          date = new Date(isoDate);
        } else {
          date = new Date(dateString);
        }
        
        if (isNaN(date.getTime())) {
          return dateString;
        }
        
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
      } catch (error) {
        console.error('日期格式化失败:', error);
        return dateString;
      }
    },
    
    // 获取HAMD严重程度描述
    getHamdSeverity(score) {
      if (score < 8) return '正常'
      if (score < 17) return '轻度抑郁'
      if (score < 24) return '中度抑郁'
      return '重度抑郁'
    },
    
    // 获取HAMA严重程度描述
    getHamaSeverity(score) {
      if (score < 7) return '无焦虑'
      if (score < 14) return '轻度焦虑'
      if (score < 21) return '中度焦虑'
      if (score < 29) return '重度焦虑'
      return '极重度焦虑'
    },
    
    // 获取YMRS严重程度描述
    getYmrsSeverity(score) {
      if (score <= 7) return '正常'
      if (score <= 13) return '轻度躁狂'
      if (score <= 19) return '中度躁狂'
      if (score <= 25) return '重度躁狂'
      return '极重度躁狂'
    },
    
    // 获取HAMD问题文本
    getHamdQuestionText(index) {
      const questions = [
        '抑郁情绪',
        '有罪感',
        '自杀',
        '入睡困难',
        '睡眠不深',
        '早醒',
        '工作和兴趣',
        '迟缓',
        '激越',
        '精神性焦虑',
        '躯体性焦虑',
        '胃肠道症状',
        '全身症状',
        '性症状',
        '疑病',
        '体重减轻',
        '自知力'
      ]
      return questions[index - 1] || `问题${index}`
    },
    
    // 获取HAMA问题文本
    getHamaQuestionText(index) {
      const questions = [
        '焦虑心境',
        '紧张',
        '害怕',
        '失眠',
        '认知功能',
        '抑郁心境',
        '躯体性肌肉症状',
        '躯体性感觉症状',
        '心血管系统症状',
        '呼吸系统症状',
        '胃肠道症状',
        '泌尿生殖系统症状',
        '自主神经症状',
        '行为表现'
      ]
      return questions[index - 1] || `问题${index}`
    },
    
    // 获取YMRS问题文本
    getYmrsQuestionText(index) {
      const questions = [
        '情绪高涨',
        '活动增多',
        '睡眠减少',
        '易激惹',
        '言语速度',
        '言语压力',
        '思维内容',
        '夸大观念',
        '注意力分散',
        '敌意',
        '夸大观念严重程度'
      ]
      return questions[index - 1] || `问题${index}`
    },
    
    // 获取评分文本描述
    getItemScoreText(score) {
      if (typeof score !== 'number') return '未作答'
      return score.toString()
    },
    
    // 获取严重程度对应的样式类
    getSeverityClass(scaleType, score) {
      // 根据不同量表类型和分数返回不同的样式类
      switch(scaleType) {
        case 'hamd':
          if (score <= 7) return 'normal'
          if (score <= 17) return 'mild'
          if (score <= 24) return 'moderate'
          return 'severe'
        case 'hama':
          if (score <= 7) return 'normal'
          if (score <= 14) return 'mild'
          if (score <= 21) return 'moderate'
          if (score <= 28) return 'severe'
          return 'very-severe'
        case 'ymrs':
          if (score <= 7) return 'normal'
          if (score <= 19) return 'mild'
          if (score <= 29) return 'moderate'
          return 'severe'
        default:
          return ''
      }
    },
    
    // 获取严重程度对应的文字描述
    getSeverityText(scaleType, score) {
      // 根据不同量表类型和分数返回不同的严重程度描述
      switch(scaleType) {
        case 'hamd':
          if (score <= 7) return '正常范围'
          if (score <= 17) return '轻度抑郁'
          if (score <= 24) return '中度抑郁'
          return '重度抑郁'
        case 'hama':
          if (score <= 7) return '正常范围'
          if (score <= 14) return '轻度焦虑'
          if (score <= 21) return '中度焦虑'
          if (score <= 28) return '重度焦虑'
          return '极重度焦虑'
        case 'ymrs':
          if (score <= 7) return '正常范围'
          if (score <= 19) return '轻度躁狂'
          if (score <= 29) return '中度躁狂'
          return '重度躁狂'
        default:
          return ''
      }
    }
  }
}
</script>

<style scoped>
.container {
  padding-bottom: 80rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  background-color: #FF7A45;
  padding: 0 28rpx;
  box-shadow: 0 2rpx 10rpx rgba(255, 122, 69, 0.3);
}

.header-left {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.header-left:active {
  background-color: rgba(255, 255, 255, 0.2);
}

.back-icon {
  color: #fff;
  font-size: 40rpx;
  font-weight: bold;
}

.header-title {
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
}

.header-right {
  width: 40rpx;
}

.assessment-container {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

/* 加载中样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
}

.loading-text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #999;
}

/* 主内容区域 */
.assessment-content {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

/* 通用卡片样式 */
.info-card,
.overview-card,
.notes-card,
.scale-card {
  background: #fff;
  padding: 30rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 25rpx;
  display: block;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

/* 患者信息样式 */
.patient-info {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.info-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
  font-size: 28rpx;
  min-width: 300rpx;
}

.info-label {
  color: #666;
  width: 140rpx;
}

.info-value {
  color: #333;
  flex: 1;
}

/* 评估概览样式 */
.assessment-overview {
  display: flex;
  flex-direction: column;
  gap: 25rpx;
}

.overview-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.overview-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.overview-label {
  color: #666;
  font-size: 28rpx;
}

.overview-value {
  font-weight: bold;
  font-size: 36rpx;
  margin-right: 15rpx;
}

.severity-text {
  font-size: 26rpx;
  color: #999;
}

/* 评估备注样式 */
.notes-content {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
  padding: 15rpx 0;
  white-space: pre-wrap;
}

/* 量表详情样式 */
.scale-details {
  display: flex;
  flex-direction: column;
  gap: 25rpx;
}

.scale-section {
  margin-bottom: 30rpx;
  padding: 20rpx;
  background-color: #fafafa;
  border-radius: 12rpx;
}

.scale-section:last-child {
  margin-bottom: 0;
}

.scale-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #666;
  margin-bottom: 20rpx;
  display: block;
}

.scale-answers {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.scale-answer-item {
  display: flex;
  align-items: center;
  padding: 15rpx 25rpx;
  background: #fff;
  border: 1rpx solid #e8e8e8;
  border-radius: 8rpx;
  font-size: 26rpx;
  transition: all 0.3s ease;
}

.scale-answer-item:active {
  background: #f0f0f0;
  transform: scale(0.98);
}

.answer-number {
  color: #666;
  margin-right: 10rpx;
  min-width: 30rpx;
}

.answer-value {
  color: #333;
  font-weight: bold;
}

/* 无数据状态 */
.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
}

.no-data-text {
  font-size: 30rpx;
  color: #999;
  padding: 20rpx;
}

/* 严重程度样式 */
.normal {
  color: #52c41a;
}

.mild {
  color: #faad14;
}

.moderate {
  color: #fa8c16;
}

.severe {
  color: #f5222d;
}

.very-severe {
  color: #722ed1;
}

/* 响应式设计 */
@media screen and (max-width: 320px) {
  .info-item {
    min-width: 100%;
  }
  
  .overview-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10rpx;
  }
  
  .overview-value {
    margin-right: 0;
  }
}
</style>